package com.components.update.util

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File

object AppUtils {

    /**
     * 安装apk
     * @param context
     * @param file
     */
    fun installApk(
        context: Context,
        file: File?,
        authority: String?
    ) {
        val intent = getInstallIntent(context, file, authority)
        context.startActivity(intent)
    }

    /**
     * 获取安装Intent
     * @param context
     * @param file
     * @param authority
     * @return
     */
    private fun getInstallIntent(
        context: Context?,
        file: File?,
        authority: String?
    ): Intent {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        val type = "application/vnd.android.package-archive"
        val uriData: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            FileProvider.getUriForFile(context!!, authority!!, file!!)
        } else {
            Uri.fromFile(file)
        }
        intent.setDataAndType(uriData, type)
        return intent
    }

}